package com.pan.basecommon.base;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.android.arouter.launcher.ARouter;
import com.pan.basecommon.BuildConfig;
import com.pan.basecommon.model.dao.DaoMaster;
import com.pan.basecommon.model.dao.DaoSession;
import com.pan.basecommon.model.dao.ReleaseOpenHelper;

import org.greenrobot.greendao.database.Database;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import dagger.android.DaggerApplication;

public abstract class BaseApplication extends DaggerApplication {

    private static BaseApplication mInstance;

    private DaoSession mDaoSession;

    private SharedPreferences mSharedPreferences;
    //全局单例线程池，一次仅运行一个线程
    private static ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    //全局定时线程池
    private static ScheduledExecutorService scheduledThreadExecutor = Executors.newScheduledThreadPool(5);
    //全局多任务线程池
    private static ExecutorService fixedThreadExecutor = Executors.newFixedThreadPool(5);

    @Override
    public void onCreate() {
        super.onCreate();
        com.pan.basecommon.log.XLog.loadLibrary();
        initARouter();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        this.mInstance = this;
        initGreenDao();
    }

    public static synchronized BaseApplication getInstance() {
        return mInstance;
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    //初始化GreenDao 数据库
    private void initGreenDao() {
        final ReleaseOpenHelper helper = new ReleaseOpenHelper(this, com.pan.basecommon.constants.Constants.DB_NAME);
        final Database db = helper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

    /**
     * 初始化路由
     */
    private void initARouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();  // 打印日志
            ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(mInstance);// 尽可能早，推荐在Application中初始化
    }

    public static Executor getSingleThreadExecutor() {
        return singleThreadExecutor;
    }

    public static ScheduledExecutorService getScheduledThreadExecutor() {
        return scheduledThreadExecutor;
    }

    public static ExecutorService getFixedThreadExecutor() {
        return fixedThreadExecutor;
    }

}
